import serial
import time
import pandas as pd

def test_serial_traffic(port, baudrate=9600, interval=0.01):
    try:
        # 打开串口
        ser = serial.Serial(port, baudrate, timeout=interval)
        print(f"成功打开串口: {port} @ {baudrate} bps")

        # 初始化变量
        bytes_received = 0
        start_time = time.time()
        data_log = []

        while True:
            # 读取数据
            received_data = ser.read(ser.in_waiting or 1)
            bytes_received += len(received_data)

            current_time = time.time()
            elapsed_time = current_time - start_time

            if elapsed_time >= interval:
                # 计算并打印传输速率
                throughput = (bytes_received / elapsed_time) * 8 / 1024  # 转换为kbps
                log_entry = {
                    'Time': current_time,
                    'Bytes Received': int(bytes_received),
                    'Elapsed Time': float(elapsed_time),
                    'Throughput (kbps)': float(throughput)
                }
                data_log.append(log_entry)
                
                print(f"已接收字节数: {bytes_received}, 经过时间: {elapsed_time:.3f}s, 吞吐量: {throughput:.2f} kbps")
                
                # 重置计数器和开始时间
                bytes_received = 0
                start_time = current_time

                # 每隔一段时间保存一次数据到CSV
                if len(data_log) % 100 == 0:  # 每1秒保存一次（假设interval=0.01）
                    save_to_csv(data_log, 'serial_traffic.csv')
                    data_log = []

    except serial.SerialException as e:
        print(f"无法打开串口: {e}")
    finally:
        if ser.is_open:
            ser.close()
            print("关闭串口")
        
        # 保存剩余数据到CSV
        if data_log:
            save_to_csv(data_log, 'serial_traffic.csv')

def save_to_csv(data, filename):
    df = pd.DataFrame(data)
    if not df.empty:
        with open(filename, mode='a', newline='') as f:
            df.to_csv(f, index=False, header=f.tell()==0,quoting=pd.io.common.constants.QUOTE_NONE)
        print(f"数据已保存到 {filename}")
def save_to_csv(data, filename):
    df = pd.DataFrame(data)
    if not df.empty:
        with open(filename, mode='a', newline='') as f:
            df.to_csv(f, index=False, header=f.tell()==0)
        print(f"数据已保存到 {filename}")

if __name__ == "__main__":
    port_name = "/dev/ttyS6"  # 根据实际情况修改串口号
    baud_rate = 115200        # 根据实际情况修改波特率
    test_serial_traffic(port_name, baud_rate)



